%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     角色工具
%%% @end
%%%-------------------------------------------------------------------
-module(util_role).

-export([
    send/1
    ,send/2
    ,pack_send/2
    ,pack_send/3

    ,role_send/2
    ,role_pack_send/3

    ,print/1
]).

-include("common.hrl").
-include("role.hrl").


%%%===================================================================
%%% API functions
%%%===================================================================

send(Bin) ->
    case get(is_role_process) of
        true -> send(get(conn_pid), Bin);
        _ -> ?ERR("发送数据时不在角色进程")
    end.

send(ConnPid, Bin) ->
    case get(send_buffer) of
        undefined -> ConnPid ! {send, Bin};
        Bins -> put(send_buffer, [Bin | Bins])
    end.

pack_send(Cmd, Data) ->
    case util_net:pack(Cmd, Data) of
        {ok, Bin} -> send(Bin);
        Error -> ?ERR("打包数据出错[Cmd:~w][Err:~w]", [Cmd, Error])
    end.

pack_send(ConnPid, Cmd, Data) ->
    case util_net:pack(Cmd, Data) of
        {ok, Bin} -> send(ConnPid, Bin);
        Error -> ?ERR("打包数据出错[Cmd:~w][Err:~w]", [Cmd, Error])
    end.


%% 发送协议到角色进程
role_send(RolePid, Bin) when is_pid(RolePid) ->
    RolePid ! {socket_proxy, Bin};
role_send(Rid, Bin) ->
    case global:whereis_name({role, Rid}) of
        Pid when is_pid(Pid) -> role_send(Pid, Bin);
        _ -> ok
    end.

%% 打包并发送协议到角色进程
role_pack_send(RolePid, Cmd, Data) when is_pid(RolePid) ->
    case util_net:pack(Cmd, Data) of
        {ok, Bin} -> role_send(RolePid, Bin);
        {error, Reason} -> ?ERR("打包数据出错[Cmd:~w][Reason:~w]", [Cmd, Reason])
    end;
role_pack_send(Rid, Cmd, Data) ->
    case global:whereis_name({role, Rid}) of
        Pid when is_pid(Pid) -> role_pack_send(Pid, Cmd, Data);
        _ -> ok
    end.



%% DEBUG下调试使用
print(Role) when is_record(Role, role) ->
    io:format(" #role{} ");
print(R) when is_tuple(R) ->
    L = tuple_to_list(R),
    io:format("{"),
    print_list(L),
    io:format("}");
print(R) when is_list(R) ->
    try io:format("\"~s\"", [R]) of
        _ -> ok
    catch
        _:_ ->
            io:format("["),
            print_list(R),
            io:format("]")
    end;
print(R) ->
    io:format("~w", [R]).

print_list([]) ->
    ok;
print_list([H | []]) ->
    print(H);
print_list([H | T]) ->
    print(H),
    io:format(", "),
    print_list(T).
